package api;

import helpers.UrlHelper;
import helpers.ValidateHelper;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.TreeMap;
import java.util.regex.Pattern;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import library.PayFee;
import library.Utils;
import models.ApiConfigModel;
import models.BlockCustomerModel;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import com.google.gson.Gson;

import entities.ApiConfig;
import entities.BlockCustomer;

@SuppressWarnings("serial")
public class GetListLinkApi extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		
		response.setContentType("application/json");
		
		TreeMap<String, Object> result = new TreeMap<String, Object>();
		
		String key = (String) request.getParameter("key");
		String c = (String) request.getParameter("c");
		String url = (String) request.getParameter("url");
		
		if (c == null || key == null) {
			result.put("status", "error");
			result.put("message", "Api key or config id is not valid.");
		} else if (url == null || url.isEmpty() || !ValidateHelper.isUrl(url)) {
			result.put("status", "error");
			result.put("message", "Url is not valid.");
		} else {
			ApiConfigModel apiConfigModel = ApiConfigModel.getInstance();
			ApiConfig apiConfig = apiConfigModel.get(c);
			if (apiConfig == null) {
				result.put("status", "error");
				result.put("message", "This config can't not found on systems.");
			} else {
				
				BlockCustomerModel blockCustomerModel = BlockCustomerModel.getInstance();
				BlockCustomer blockCustomer = blockCustomerModel.get(apiConfig.getUserBlog());
				
				if (blockCustomer == null) {
				
					TreeMap<String, Object> dataMap = new TreeMap<String, Object>();
					dataMap.put("url", url);
					
					List<String> links = new ArrayList<String>();
					
					/*********************    Get Content from url *********************/
					Document doc = null;
					String charset="UTF-8";
					
					doc = Jsoup.parse(Utils.GetHtml(url, charset));
	
					int index = doc.select("meta").toString().toLowerCase()
							.indexOf("charset=");
					if (index != -1) {
						charset = doc.select("meta").toString().substring(index + 8)
								.replaceAll("[^\\'\\\"0-9a-zA-Z\\-\\_]+[\\w\\W]+", "")
								.replaceAll("[\\'\\\"]+", "");
					}
					//
	
					doc = Jsoup.parse(Utils.GetHtml(url, charset));
					
					try{
						
						Elements a = doc.select(apiConfig.getLinkSelecter());
						
						for (int i = 0; i < a.size(); i++) {
							if(!Pattern.matches("^http://[\\w\\W]+$", a.get(i).attr("href")))
							{
								links.add("http://"+UrlHelper.fomatDomains(url) + a.get(i).attr("href"));
							} else {
								links.add(a.get(i).attr("href"));
							}
						}
						
					} catch (Exception e) {
						result.put("status", "error");
						result.put("message", "Error link selector");
					}
					
					dataMap.put("links", links);
					
					
					/********************* End Get Content from url *********************/
					
					result.put("status", "success");
					result.put("data", dataMap);
					
					//Tru tien credit
					String note = "Pay 1 credit to get list link from url " + url;
					PayFee.payFee(1, apiConfig.getUserBlog(), note);
				} else {
					result.put("status", "error");
					result.put("message", "You don't have enough credit to get content or your account has been block.");
				}
			}
		}
		
		String json = new Gson().toJson(result);
		response.getWriter().println(json);
	}
}
